package cn.educate.servlet;

import cn.educate.utils.DBUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取前端参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = request.getParameter("role");       // 教师/学生
        String gender = request.getParameter("gender");   // 男/女

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            // 严格校验用户名、密码、角色、性别
            String sql = "SELECT id FROM users " +
                    "WHERE name = ? AND password = ? AND occupation = ? AND gender = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.setString(3, role);
            pstmt.setString(4, gender);

            rs = pstmt.executeQuery();

            if (rs.next()) {
                // 登录成功，根据角色跳转
                if ("教师".equals(role)) {
//                    response.sendRedirect("teacherIndex.jsp?username=" + username + "&gender=" + gender);
                    response.sendRedirect("teacher/teacherIndex.jsp");
                } else {
//                    response.sendRedirect("student.jsp?username=" + username + "&gender=" + gender);
                    response.sendRedirect("student/student.jsp");
                }
            } else {
                // 登录失败提示
                response.getWriter().println("登录失败！请检查用户名、密码、角色和性别是否匹配<br>");
                response.getWriter().println("重新登录");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().println("数据库错误！请联系管理员");
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
    }
}